package com.loukou.lkt.lkt.datasource;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSource;


public class DynamicDataSource extends AbstractRoutingDataSource {

	@Override
	protected Object determineCurrentLookupKey() {

		return DynamicDataSourceHolder.getDataSourceName();
	}

	public void addTargetDataSources(String targetDataSourcesKey,String url,String userName,String password){
		if(!getTargetDataSources().containsKey(targetDataSourcesKey)){
			
			addDataSource(targetDataSourcesKey, buildDataSource(url,userName,password));
		}
	}
	
	private DataSource buildDataSource(String url,String userName,String password){
		DruidDataSource ds = new DruidDataSource();
		ds.setUrl(url);
		ds.setUsername(userName);
		ds.setPassword(password);
		ds.setInitialSize(1);
		ds.setMinIdle(1);
		ds.setMaxActive(20);
		ds.setMaxWait(60000);
		ds.setTimeBetweenEvictionRunsMillis(60000);
		ds.setMinEvictableIdleTimeMillis(300000);
		ds.setValidationQuery("SELECT 'x'");
		ds.setTestWhileIdle(true);
		ds.setTestOnBorrow(false);
		ds.setTestOnReturn(false);
		ds.setPoolPreparedStatements(true);
		ds.setMaxPoolPreparedStatementPerConnectionSize(20);
		
		return ds;
	}
}
